from flask import current_app
from flask import g, jsonify
from flask import render_template
from flask import request

from info import constants
from info import db
from info.models import User, News
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import profile_blu
from info.utils.common import user_login_data


@profile_blu.route('/collect_info')
@user_login_data
def collect_info():
    user = g.user
    current_page=1
    total_page=1
    page=request.args.get("p",1)
    news_list=[]
    try:
        paginate=user.collection_news.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        total_page=paginate.pages
        current_page=paginate.page
        news_list=paginate.items
    except Exception as e:
        current_app.logger.error(e)
        page=1
    news_dict_list = []
    for new in news_list:
        news_dict_list.append(new.to_basic_dict)
    data={
        "total_page":total_page,
        "current_page":current_page,
        "news_dict_list":news_dict_list
    }
    return render_template('news/../../static/news/html/../../templates/news/user_collection.html', data=data)


@profile_blu.route('/pass_info',methods=['POST','GET'])
@user_login_data
def pass_info():
    if request.method=='GET':
        return render_template('news/user_pass_info.html')
    user=g.user
    old_password=request.json.get('old_password')
    new_password=request.json.get('new_password')
    new_password2=request.json.get('new_password2')
    if not all([old_password,new_password,new_password2]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='密码输入错误')
    user.password=new_password
    return jsonify(errno=RET.OK, errmsg='保存成功')


@profile_blu.route('/pic_info',methods=['POST','GET'])
@user_login_data
def pic_info():
    user=g.user
    if request.method=='GET':
        return render_template('news/user_pic_info.html',data={"user":user.to_dict()})
    try:
        avatar_url=request.files.get('avatar_url').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        key=storage(avatar_url)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传头像失败')
    user.avatar_url=key
    data={
        "avatar_url":constants.QINIU_DOMIN_PREFIX+key
    }
    return jsonify(errno=RET.OK, data=data)


@profile_blu.route('/user_base',methods=['POST','GET'])
@user_login_data
def user_base():
    if request.method=='GET':
        return render_template('news/user_base_info.html')
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    if not all ([nick_name,signature,gender]):
        # return jsonify(errno=RET.NODATA,errmsg='参数不全')
        return jsonify(errno=RET.NODATA, errmsg='参数不全')
    if gender not in ["MAN","WOMEN"]:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    user=g.user
    user.nick_name=nick_name
    user.signature=signature
    user.gender=gender
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
    data={
        "user":user.to_dict()
    }
    return jsonify(errno=RET.OK, data=data)


@profile_blu.route('/user')
@user_login_data
def user_center():
    user=g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='您还没有登录')
    data={
        'user':user.to_dict()
    }
    return render_template('news/user.html',data=data)